<template>
  <div id="userManager">
    <div class="aspace">
      <a-card>
        <a-space :size="20">
          <a-input
            :style="{ width: '320px' }"
            @keyup.enter="list(formData)"
            placeholder="标题"
            v-model="formData.title"
            allow-clear
          />
          <a-input
            :style="{ width: '320px' }"
            @keyup.enter="list(formData)"
            placeholder="内容"
            v-model="formData.content"
            allow-clear
          />
          <a-button type="primary" @click="list(formData)">查询</a-button>
          <a-button @click="handleReset">重置</a-button>
        </a-space>
      </a-card>
    </div>
    <div class="atable">
      <a-card>
        <div style="margin-bottom: 10px">
          <a-button type="primary" @click="handleAdd">新建</a-button>
          &nbsp;&nbsp;&nbsp;
          <a-dropdown v-if="selectedKeys.length">
            <a-button
              >批量操作
              <icon-down />
            </a-button>
            <template #content>
              <a-doption @click="handleBatchToBank(1)">
                <template #icon>
                  <icon-plus-circle-fill />
                </template>
                批量加入题库
              </a-doption>
              <a-doption @click="handleBatchToBank(0)" style="color: red">
                <template #icon>
                  <icon-close-circle-fill />
                </template>
                批量从题库移除
              </a-doption>
              <a-doption @click="handleBatchDel" style="color: red">
                <template #icon>
                  <icon-close-circle-fill />
                </template>
                批量删除题目
              </a-doption>
            </template>
          </a-dropdown>
          <a-modal v-model:visible="visible" :footer="false" :width="1200">
            <QuestionModal
              :title="title"
              :closeModal="closeModal"
              :isUpdate="isUpdate"
              :list="list"
              ref="chFun"
            ></QuestionModal>
            <template #title>
              {{ title }}
            </template>
          </a-modal>
          <a-modal
            v-model:visible="batchToBankVisible"
            :title="optBankTitle"
            @ok="handleBatchToBankOk"
          >
            <div style="text-align: center">
              <a-select
                :style="{ width: '320px' }"
                placeholder="请选择题库"
                @change="handleBatchBank"
              >
                <a-option
                  v-for="e in questionBankList"
                  :value="e.id"
                  :key="e.id"
                  >{{ e.title }}
                </a-option>
              </a-select>
            </div>
          </a-modal>
        </div>
        <a-table
          :columns="columns"
          :data="data"
          :row-selection="rowSelection"
          row-key="id"
          v-model:selectedKeys="selectedKeys"
          :pagination="{ total }"
          @page-change="handlePageChange"
        >
          <template #tagslot="{ record }">
            <a-tag
              v-for="e in record.tags"
              :key="e"
              color="arcoblue"
              style="margin: 2px"
              >{{ e }}
            </a-tag>
          </template>
          <template #picslot="{ record }">
            <img :src="record.picture" width="50px" />
          </template>
          <template #optional="{ record }">
            <a-link @click="handleEdit(record)">修改</a-link>&nbsp;
            <a-link @click="handleEdit(record)">设置题库</a-link>&nbsp;
            <a-popconfirm
              content="确认删除？"
              type="info"
              @ok="handleDel(record)"
            >
              <a-link style="color: red">删除</a-link>
            </a-popconfirm>
          </template>
        </a-table>
      </a-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch } from "vue";
import {
  QuestionBankControllerService,
  QuestionBankQuestionControllerService,
  QuestionControllerService,
} from "../../../generated";
import QuestionModal from "@/views/question/QuestionModal.vue";
import notification from "@arco-design/web-vue/es/notification";
import { Modal } from "@arco-design/web-vue";
import message from "@arco-design/web-vue/es/message";

let formData = reactive({
  current: 1,
  title: "",
  content: "",
});
// 被选择项
const selectedKeys = ref([]);
//
const rowSelection = reactive({
  type: "checkbox",
  onlyCurrent: false,
});
// 记录总数
const total = ref(10);
// 列名
const columns = [
  {
    title: "标题",
    align: "center",
    dataIndex: "title",
  },
  {
    title: "内容",
    align: "center",
    dataIndex: "content",
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "标签字段",
    align: "center",
    dataIndex: "tags",
    slotName: "tagslot",
  },
  {
    title: "答案",
    align: "center",
    dataIndex: "answer",
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "创建时间",
    align: "center",
    dataIndex: "createTime",
  },
  {
    title: "操作",
    align: "center",
    slotName: "optional",
  },
];
// 表格数据
const data = reactive([]);
// 控制弹窗
const visible = ref(false);
const batchToBankVisible = ref(false);
// 弹窗标题
const title = ref("");
// 修改值回显
const editoption = reactive({});
// 题库列表
const questionBankList = ref([]);
// 编辑标志
const isUpdate = ref(false);
// 将题目批量加入题库
const batchToBankList = ref({
  questionList: [],
  questionBankId: "",
});

function handleBatchDel() {
  Modal.info({
    title: "批量删除题目",
    content: "确定删除这些题目？",
    alignCenter: false,
    width: 300,
    onOk: () => {
      QuestionBankQuestionControllerService.batchDeleteQuestionUsingPost({
        questionIdList: selectedKeys.value,
      }).then((res) => {
        if (res.code === 0) {
          message.success("批量删除成功");
          handleReset();
        }
      });
    },
  });
}

function handleBatchToBankOk() {
  batchToBankList.value.questionList = [...selectedKeys.value];
  if (optBankStatus.value) {
    console.log("调用添加接口啦", batchToBankList.value);
    QuestionBankQuestionControllerService.batchAddToBankUsingPost({
      questionBankId: batchToBankList.value.questionBankId,
      questionIdList: batchToBankList.value.questionList,
    }).then((res) => {
      if (res.code === 0) {
        message.success("批量加入成功");
      }
    });
  } else {
    console.log("调用移除接口啦", batchToBankList.value);
    QuestionBankQuestionControllerService.batchRemoveFromBankUsingPost({
      questionBankId: batchToBankList.value.questionBankId,
      questionIdList: batchToBankList.value.questionList,
    }).then((res) => {
      if (res.code === 0) {
        message.success("批量移除成功");
      }
    });
  }
  selectedKeys.value.length = 0;
}

function handleBatchBank(value: any) {
  batchToBankList.value.questionBankId = value;
}

const optBankTitle = ref("");
let optBankStatus = ref(false);

function handleBatchToBank(value) {
  batchToBankVisible.value = true;
  optBankTitle.value = value ? "批量加入题库" : "批量移出题库";
  optBankStatus.value = value;
}

function list(args: any) {
  QuestionControllerService.listQuestionByPageUsingPost({
    ...args,
  }).then((res) => {
    data.length = 0;
    total.value = res.data.total;
    Object.assign(data, res.data.records);
    for (const e of data) {
      e.tags = JSON.parse(e.tags);
    }
  });
}

function handlePageChange(page: number) {
  formData.current = page;
  list(formData);
}

function clearContent() {
  Object.assign(formData, {
    current: 1,
    title: "",
    content: "",
  });
}

function handleReset() {
  clearContent();
  list(formData);
}

function handleAdd() {
  title.value = "🚀新建题目🚀";
  isUpdate.value = false;
  visible.value = true;
}

function handleEdit(record: any) {
  title.value = "🍭编辑题目🍭";
  isUpdate.value = true;
  visible.value = true;
  Object.assign(editoption, record);
}

function handleDel(record) {
  QuestionControllerService.deleteQuestionUsingPost({
    id: record.id,
  }).then((res) => {
    if (res.code === 0) {
      notification.success("删除成功");
      clearContent();
      list(formData);
    } else {
      notification.error("删除失败");
    }
  });
}

/**
 * 关闭弹窗
 */
function closeModal() {
  visible.value = false;
}

/**
 * 加载所有题库
 */
function onloadAllQuestionBankList() {
  QuestionBankControllerService.listQuestionBankByPageUsingPost({
    pageSize: 1000,
  }).then((res) => {
    questionBankList.value = res.data.records;
  });
}

onMounted(() => {
  list(formData);
  onloadAllQuestionBankList();
});

const chFun = ref(null);
watch(visible, (newv, oldv) => {
  if (newv && isUpdate.value) {
    console.log("窗口打开，当前为编辑状态=>", newv);
    chFun.value?.handleEdit(editoption);
  } else if (newv) {
    chFun.value?.handleAdd({
      title: "",
      content: "",
      tags: [],
      answer: "",
    });
  }
});
</script>

<style scoped>
#userManager {
  margin-left: 80px;
  margin-right: 80px;
}

.atable {
  margin-top: 20px;
}

a {
  text-decoration: none;
}

.arco-dropdown-open .arco-icon-down {
  transform: rotate(180deg);
}
</style>
